import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:jtsell_app/config/app_config.dart';
import 'package:jtsell_app/entity/cart_item_entity.dart';
import 'package:jtsell_app/provider/cart_list_model.dart';
import 'package:provider/provider.dart';

import 'cart_item_widget.dart';

class CartListWidget extends StatelessWidget {
  CartListModel model;

  @override
  Widget build(BuildContext context) {
    return Consumer<CartListModel>(
        builder: (BuildContext context, CartListModel cartListModel, Widget child) {
      model = cartListModel;

      if (model == null || model.items.isEmpty) {
        return Expanded(child: Center(child: Text("暂无数据")));
      }

      return Expanded(
        flex: 1,
        child: ListView.builder(
          padding: EdgeInsets.all(0),
          itemCount: model.itemsCount,
          itemExtent: 93,
          itemBuilder: (BuildContext context, int index) {
            CartItemEntity item = model.items[index];

            ///
            /// 滑动删除
            ///
            return Dismissible(
              resizeDuration: Duration(milliseconds: 100),
              key: Key(item.productName),
              direction: DismissDirection.endToStart,
              onDismissed: (DismissDirection direction) {
                model.removeItem(index);
                Scaffold.of(context).showSnackBar(SnackBar(
                  content: Text("${item.productName}   成功移除"),
                  backgroundColor: Theme.of(context).primaryColor,
                  duration: Duration(seconds: 1),
                ));
              },
              background: Container(
                padding: EdgeInsets.only(right: ScreenUtil().setWidth(50)),
                color: AppConfig.THEME_COLOR,
                child: Stack(
                  alignment: Alignment.centerRight,
                  children: <Widget>[
                    Icon(
                      Icons.delete_forever,
                      color: Colors.white,
                    )
                  ],
                ),
              ),
              child: CartItemWidget(model.items[index],
                  addCount: _addCount,
                  downCount: _downCount,
                  index: index,
                  switchChaned: _switchChanged),
            );
          },
        ),
      );
    });
  }

  _switchChanged(int i) {
    model.switchSelect(i);
  }

  _addCount(int i) {
    model.addCount(i);
  }

  _downCount(int i) {
    model.downCount(i);
  }
}
